/* 
 * Copyright 2011 QDSS.org. All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.qdss.oapi4j.base;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.qdss.oapi4j.util.ApiUtils;
import org.xml.sax.InputSource;

/**
 * XML结果集
 * 
 * @author <a href="mailto:zhaofang123@gmail.com">Zhao Fangfang</a>
 * @date 2011-3-20
 * @version $Id: XmlResult.java 39 2011-09-27 10:41:37Z zhaofang123@gmail.com $
 */
public class XmlResult extends BaseResult<Element> {

	private Element rootElement;
	
	/**
	 * @param result
	 * @param invokeTime
	 * @param headers
	 */
	public XmlResult(String result, int invokeTime, Header[] headers) {
		super(result, invokeTime, headers);
	}
	
	public Element rootValue() {
		if (rootElement == null) {
			String raw = getRawResult();
			// TODO 处理Unicode编码
			try {
				rootElement = buildRootElement(raw, false);
			} catch (Exception ex) {
				// <itemName>12*30扎口胶带包装带封箱胶扎口带胶带彩色扎口机胶带 </itemName>
				if (ex instanceof DocumentException) {
					raw = replaceUnicode(raw);
					try {
						rootElement = buildRootElement(raw, true);
					} catch (Exception ex2) {
						throw new BadResultException("Bad XML result2: " + getRawResult(), ex2);
					}
				} else {
					throw new BadResultException("Bad XML result: " + getRawResult(), ex);
				}
			}
		}
		return rootElement;
	}
	
	public Element nodeValue(String path) {
		return (Element) rootValue().selectSingleNode(path);
	}
	
	public boolean hasValue(String path) {
		return nodeValue(path) != null;
	}
	
	public String getStringValue(String path) {
		Element node = nodeValue(path);
		if (node == null) {
			throw new NoMatchValueException("No value in path: " + path);
		}
		return node.getText();
	}

	public Integer getIntValue(String path) {
		String s = getStringValue(path);
		if (s == null) {
			throw new NoMatchValueException("No value in path: " + path);
		}
		return Integer.parseInt(s);
	}

	public Long getLongValue(String path) {
		String s = getStringValue(path);
		if (s == null) {
			throw new NoMatchValueException("No value in path: " + path);
		}
		return Long.parseLong(s);
	}
	
	public Double getDoubleValue(String path) {
		String s = getStringValue(path);
		if (s == null) {
			throw new NoMatchValueException("No value in path: " + path);
		}
		return Double.parseDouble(s);
	}
	
	public String getError() {
		throw new UnsupportedOperationException();
	}
	
	public boolean hasError() {
		throw new UnsupportedOperationException();
	}
	
	/**
	 * 替换Unicode字符
	 * 
	 * @param source
	 * @return
	 */
	static String replaceUnicode(String source) {
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
//		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("□", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("",/*有值!*/ StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
//		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("",/*有值!*/ StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("",/*有值!*/ StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		source = source.replaceAll("", StringUtils.EMPTY);
		return source;
	}
	
	/**
	 * @param source
	 * @param forceEncoding
	 * @return
	 * @throws DocumentException
	 */
	static Element buildRootElement(String source, boolean forceEncoding) throws Exception {
		if (!forceEncoding) {
			return DocumentHelper.parseText(source).getRootElement();
		}
		
		InputStream stream = new ByteArrayInputStream(source.getBytes());
		Charset charset = Charset.forName("UTF-8");
		Reader reader = new BufferedReader(new InputStreamReader(stream, charset));
		InputSource inSource = new InputSource(reader);
		
		SAXReader saxReader = ApiUtils.getFastSAXReader().getSAXParser();
		try {
			Document document = saxReader.read(inSource);
			return document.getRootElement();
		} finally {
			ApiUtils.getFastSAXReader().release(saxReader);
		}
	}
}
